import {DEFAULT_CACHE_PREFIX, DEFAULT_CACHE_TIME} from "./token";

interface CreateStorageOption {
    prefixKey?: string,
    storage?: Storage
}

export const createStorage = (option: CreateStorageOption = {}) => {
    const {prefixKey = DEFAULT_CACHE_PREFIX, storage = sessionStorage} = option;

    class WebStorage {
        storage: Storage;
        prefixKey: string;

        constructor() {
            this.storage = storage;
            this.prefixKey = prefixKey
        }

        getKey(key: string) {
            return `${this.prefixKey}${key}`.toUpperCase()
        }

        remove(key: string) {
            this.storage.removeItem(this.getKey(key))
        }

        set(key: string, value: any, expire: number = DEFAULT_CACHE_TIME) {
            const stringData = JSON.stringify({
                value,
                expire: expire > 0 ? Date.now() + expire * 1000 : -1
            })
            this.storage.setItem(this.getKey(key), stringData)
        }

        get(key: string, def: any = null) {
            const realKey = this.getKey(key);
            const item = this.storage.getItem(realKey);
            if (item) {
                try {
                    const {value, expire} = JSON.parse(item);
                    if (expire === -1 || expire > Date.now()) {
                        return value
                    }
                    this.remove(key)
                } catch (e) {
                    return def
                }
            }
            return def
        }

        clear() {
            this.storage.clear()
        }
    }

    return new WebStorage()
}